import java.util.Arrays;

/**
 * 
 * 二分法查询
 * 
 */
public class 二分法查询 {
    
    public static void main(String[] args) {

        int[] arr =  new int[]{30,20,50,10,80,9,7,12,100,40,8};
        Arrays.sort(arr);

        System.out.println(Arrays.toString(arr));
        //排序后查找

        System.out.println(divideSerach(arr, 40));

    }

    private static int divideSerach(int[] arr, int target){

        int left = 0;
        int right = arr.length -1;

        while (right >= left) {
            
            int middle = (right+left) / 2;

            if(arr[middle] == target){

                return middle;
            } else if(arr[middle] > target){

                //往小的区域寻找
                right = middle -1;
            } else {

                //往大的区域寻找
                left = middle +1;

            }

        }


        return -1;

    }
}
